part of 'component.dart';

class CodeField extends StatefulWidget {
  const CodeField({
    Key? key,
    required this.controller,
    this.isNeedBorder = false,
    this.height,
  }) : super(key: key);
  final TextEditingController controller;
  final bool isNeedBorder;
  final double? height;
  @override
  _CodeFieldState createState() => _CodeFieldState();
}

class _CodeFieldState extends State<CodeField> {
  String actionText = '获取验证码';
  int timeCount = 60;
  Timer? timer;
  bool isSending = false;
  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
    timer?.cancel();
  }

  void sendAction() {
    if (isSending) {
      return;
    }
    isSending = true;
    timer = Timer.periodic(const Duration(seconds: 1), (_) {
      if (timeCount == 0) {
        isSending = false;
        timer?.cancel();
        timeCount = 60;
        actionText = '获取验证码';
      } else {
        timeCount--;
        actionText = '${timeCount}s';
      }
      setState(() {});
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: widget.height ?? 50.r,
      alignment: Alignment.center,
      decoration: widget.isNeedBorder
          ? BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(5),
              border: Border.all(color: ColorsUtil.content, width: 0.5))
          : null,
      child: TextField(
        maxLength: 10,
        keyboardType: TextInputType.number,
        textAlignVertical: TextAlignVertical.center,
        decoration: InputDecoration(
          isCollapsed: true,
          counterText: '',
          contentPadding: widget.isNeedBorder
              ? EdgeInsets.symmetric(horizontal: 10.r)
              : EdgeInsets.zero,
          suffixIcon: InkWell(
            onTap: sendAction,
            child: Padding(
              padding: EdgeInsets.only(right: widget.isNeedBorder ? 10.r : 0),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    actionText,
                    style: TextStyle(
                        color: isSending
                            ? const Color(0xff999999)
                            : ColorsUtil.blue,
                        fontSize: 14.sp),
                  ),
                ],
              ),
            ),
          ),
          hintText: '请输入短信验证码',
          hintStyle: TextStyle(color: const Color(0xffbbbbbb), fontSize: 15.sp),
          enabledBorder: widget.isNeedBorder ? InputBorder.none : getBorder(),
          disabledBorder: widget.isNeedBorder ? InputBorder.none : getBorder(),
          focusedBorder: widget.isNeedBorder ? InputBorder.none : getBorder(),
        ),
      ),
    );
  }

  InputBorder getBorder() {
    return const UnderlineInputBorder(
        borderSide: BorderSide(color: Color(0xffeeeeee)));
  }
}
